package com.artron.mediaartron.ui.fragment.made;

import android.graphics.Bitmap;
import android.support.annotation.DrawableRes;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.image.ImageUtils;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.FrameData;
import com.artron.mediaartron.data.entity.UploadMaterialData;
import com.artron.mediaartron.data.entity.User;
import com.artron.mediaartron.data.entity.Works;
import com.artron.mediaartron.data.net.NetConstant;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.task.AddShoppingCartTask;
import com.artron.mediaartron.data.task.MaterialLibraryTask;
import com.artron.mediaartron.data.production.FrameConstant;
import com.artron.mediaartron.data.production.SuitableSizeHelper;
import com.artron.mediaartron.ui.activity.CustomSelectionActivity;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.fragment.dialog.ProgressDialogFragment;
import com.artron.mediaartron.ui.fragment.factory.HomeFragmentFactory;
import com.artron.mediaartron.ui.helper.ThrottleFirstClickHelper;
import com.artron.mediaartron.ui.widget.PagerIndicator;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;

import static android.R.attr.data;
import static com.artron.mediaartron.ui.activity.CustomSelectionActivity.POSTER;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-10-11.
 */
public class PreviewFragment extends BaseStaticFragment implements View.OnClickListener {

    @BindView(R.id.PreviewFragment_pager)
    protected ViewPager mViewPager;
    @BindView(R.id.PreviewFragment_pager_indicator)
    protected PagerIndicator mPagerIndicator;
    @BindView(R.id.PreviewFragment_btn_next)
    protected Button mBtnNext;

    private int mFrameResourceId;
    private String mImagePath;
    private float mWidth;
    private float mHeight;
    private ProgressDialogFragment mProgressDialogFragment;
    private int mType;
    private String mMaterialId;
    private BottomSheetDialog mDialogBuy;
    private boolean isStartShoppingCart = true;

    public static PreviewFragment newInstance(int resource, String path, float width,
                                              float height, int type, String materialId) {
        PreviewFragment fragment = new PreviewFragment();
        fragment.init(resource, path, width, height, type, materialId);
        return fragment;
    }

    private void init(int resource, String path, float width, float height, int type, String materialId) {
        this.mFrameResourceId = resource;
        this.mImagePath = path;
        this.mWidth = width;
        this.mHeight = height;
        this.mType = type;
        this.mMaterialId = materialId;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_perview;
    }

    @Override
    protected void initView() {
        mBtnNext.setOnClickListener(this);

        mViewPager.setAdapter(new PagerAdapter() {

            private LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);

            @Override
            public int getCount() {
                return 3;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View inflate = mLayoutInflater.inflate(R.layout.item_pager_preview, container, false);
                ImageView ivBg = (ImageView) inflate.findViewById(R.id.ItemPagerPreview_iv_bg);
                ImageView ivFrame = (ImageView) inflate.findViewById(R.id.ItemPagerPreview_iv_frame);
                ImageView ivImage = (ImageView) inflate.findViewById(R.id.ItemPagerPreview_iv_image);
                initImageWidthAndHeight(ivFrame, ivImage);

                ivBg.setImageResource(getResourceOfPosition(position));
                ivFrame.setImageResource(mFrameResourceId);
                Bitmap clipBitmap = SuitableSizeHelper.getHelper().getClipBitmap();
                if (clipBitmap != null) {
                    ivImage.setImageBitmap(clipBitmap);
                } else {
                    ImageUtils.setUrl(ivImage, mImagePath);
                }

                container.addView(inflate);

                return inflate;
            }

            private void initImageWidthAndHeight(ImageView ivFrame, ImageView ivImage) {
                float width500 = UIUtils.getResources().getDisplayMetrics().widthPixels / 2.5f;
                float per = width500 / 500.f;

                ViewGroup.LayoutParams frameParams = ivFrame.getLayoutParams();
                FrameLayout.LayoutParams imageParams = (FrameLayout.LayoutParams)
                        ivImage.getLayoutParams();

                int type = mType;
                if (type == CustomSelectionActivity.CUSTOM_MADE) {
                    int distance = (int) FrameConstant.BLANK_CUSTOM_MADE;
                    frameParams.height = (int) (per * mHeight);
                    frameParams.width = (int) (per * mWidth);
                    imageParams.height = (int) ((mHeight - distance) * per);
                    imageParams.width = (int) ((mWidth - distance) * per);
                } else if (type == CustomSelectionActivity.POSTER) {
                    frameParams.height = (int) (per * mHeight + 50);
                    frameParams.width = (int) (per * mWidth  + 50);
                    imageParams.height = (int) (mHeight * per);
                    imageParams.width = (int) (mWidth * per);
                    imageParams.leftMargin = 5;
                    imageParams.topMargin = 5;
                }

                ivFrame.setLayoutParams(frameParams);
                ivImage.setLayoutParams(imageParams);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(((View) object));
            }
        });

        mPagerIndicator.setViewPager(mViewPager);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.PreviewFragment_btn_next:
                FrameData frameData = SuitableSizeHelper.getHelper().getFrameData();
                String contentImage = frameData.getImage().getContentImage();
                uploadImage(frameData, contentImage);
                break;
            case R.id.ItemBottomAddVideo_tv_add_shopping_cart:
                addShoppingCart();
                break;
            case R.id.ItemBottomAddVideo_tv_buy:
                GeneralActivity.start(mContext, GeneralActivity.ORDER, "确认订单");
                break;
            case R.id.ItemBottomAddVideo_tv_cancel:
                mDialogBuy.dismiss();
                break;
        }
    }

    @DrawableRes
    private int getResourceOfPosition(int position) {
        if (position == 0) {
            return R.drawable.ic_dinling_room;
        } else if (position == 1){
            return R.drawable.ic_living_room;
        } else if (position == 2) {
            return R.drawable.ic_bedroom;
        }
        return R.drawable.ic_dinling_room;
    }

    private void uploadImage(final FrameData frameData, String contentImage) {
        MaterialLibraryTask task = new MaterialLibraryTask();
        User user = AppProfile.getUserInfo().getUser();
        mProgressDialogFragment = ProgressDialogFragment.newInstance("上传图片中，请稍等");
        mProgressDialogFragment.show(getChildFragmentManager(), mProgressDialogFragment.getOurTag());

        // 选择素材库的图片
        if (contentImage.contains("http:") && !TextUtils.isEmpty(mMaterialId)) {
            buildDataAndStartNextActivity(mMaterialId, frameData);
            return;
        }

        task.uploadMaterial(user.getPassId(), NetConstant.CLIENT_CODE,
                contentImage, new Action1<UploadMaterialData>() {
                    @Override
                    public void call(UploadMaterialData data) {
                        buildDataAndStartNextActivity(data.getId(), frameData);
                    }
                });
    }

    private void buildDataAndStartNextActivity(String id, FrameData frameData) {
        SuitableSizeHelper helper = SuitableSizeHelper.getHelper();
        Works works = helper.getWorks();
        Works.MaterialEditBean bean = works.getEditBean(0);
        if (bean == null) {
            bean = works.addEditBean(new Works.MaterialEditBean())
                    .getEditBean(0);
        }
        String typeCode;
        if (mType == POSTER) {
            typeCode = "haibao";
        } else {
            typeCode = "kuanghua";
        }

        bean.setMaterialId(id);
        works.setWorksName(frameData.getTitle())
                .setWorksPrice(frameData.getPrice())
                .setWorksTypeCode(typeCode)
                .setWorksShape(frameData.getShapeType())
                .setWorksColor("")
                .setWorksSize(frameData.getSize())
                .setWorksQuantity(1)
                .setSkuCode(frameData.getSku())
                .setMaterialId(id)
                .setWorksClientCode("android")
                .setWorksChannelCode("artron");
        mProgressDialogFragment.dismiss();

        //        GeneralActivity.start(mContext, GeneralActivity.ADD_VIDEO, "添加视频");
        //TODO 以后需要删除的逻辑
        //购买相关的底部弹框
        mDialogBuy = new BottomSheetDialog(mContext);
        mDialogBuy.setContentView(R.layout.layout_bottom_add_shopping_cart_or_buy);

        View btnShoppingCart = mDialogBuy.findViewById(R.id.ItemBottomAddVideo_tv_add_shopping_cart);
        if (btnShoppingCart != null) {
            ThrottleFirstClickHelper.throttleFirst(btnShoppingCart, this);
        }

        View btnBuy = mDialogBuy.findViewById(R.id.ItemBottomAddVideo_tv_buy);
        if (btnBuy != null) {
            ThrottleFirstClickHelper.throttleFirst(btnBuy, this);
        }

        View btnCancel = mDialogBuy.findViewById(R.id.ItemBottomAddVideo_tv_cancel);
        if (btnCancel != null) {
            btnCancel.setOnClickListener(this);
        }

        mDialogBuy.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
        mDialogBuy.show();
    }

    private void addShoppingCart() {
        final ProgressDialogFragment fragment =  ProgressDialogFragment.newInstance("正在加入购物车");
        fragment.show(getChildFragmentManager(), fragment.getOurTag());
        fragment.setOnBackPressListener(new Action0() {
            @Override
            public void call() {
                isStartShoppingCart = false;
            }
        });

        SuitableSizeHelper helper = SuitableSizeHelper.getHelper();
        Works works = helper.getWorks();
        Observable<Response> api = AddShoppingCartTask.addShoppingCart(works);
        RetrofitHelper.subscript(api, new Action1<Response>() {
            @Override
            public void call(Response response) {

                if (isStartShoppingCart) {
                    HomeFragmentFactory.getInstance().updateShoppingCart();
                    GeneralActivity.start(mContext, GeneralActivity.SHOPPING_CART,
                            "购物车");
                }

                fragment.dismiss();
            }
        });
    }
}
